﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：EncryptService.cs
// 功能描述：TongTongMall.MallWeb.Core
// 
// Create User：jym 2017/02/28
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using TEC.Public.Common;
using TongTongMall.Dependecy;

namespace TongTongMall.MallWeb.Core
{
    public interface IEncryptService : ISingletonDependency
    {
        string Encrypt(string key, string content);

        string Md5Encrypt(string content);

        long ConvertDateTimeToUinx(DateTime time);

        string PwdEncrypt(string orginpwd, byte[] pwdkey);
        string PwdEncrypt(string orginpwd, string pwdkey);

    }

    public class EncryptService : IEncryptService
    {
        public long ConvertDateTimeToUinx(DateTime time)
        {
            DateTime unixZero = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
            int seconds = (int)(time - unixZero).TotalSeconds;
            return seconds;
        }

        public string Encrypt(string key, string content)
        {
            DesHelper desHelper = new DesHelper(key);
            byte[] encryptPwdBytes = SHA512Helper.SHA512Encode(desHelper.Encrypt(Encoding.UTF8.GetBytes(content)));
            return HexEncode(encryptPwdBytes);
        }

        public string Md5Encrypt(string content)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(Encoding.Default.GetBytes(content));
            return HexEncode(result);
        }

        private static string HexEncode(byte[] bytes)
        {
            string result = "";
            foreach (var i in bytes)
            {
                result += i.ToString("X").PadLeft(2, '0');
            }
            return result;
        }

        public string PwdEncrypt(string orginpwd, string pwdkey)
        {
            var aeskeyiv = AESCryptographyHelper.FromBytesToAesKeyIV(pwdkey.FromBase64String());
            return orginpwd.EncryptAES(aeskeyiv).ToBase64String().GetSHA512String().GetSHA512String();
        }
        public string PwdEncrypt(string orginpwd, byte[] pwdkey)
        {
            var aeskeyiv = AESCryptographyHelper.FromBytesToAesKeyIV(pwdkey);
            return orginpwd.EncryptAES(aeskeyiv).ToBase64String().GetSHA512String().GetSHA512String();
        }
    }
}
